package com.filetransfer.api.upload;
import java.io.IOException;

import lombok.Getter;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

import org.jetbrains.annotations.NotNull;
public class ProgressRequestBody extends RequestBody {
    private final RequestBody requestBody;
    private final ProgressListener progressListener;
    public ProgressRequestBody(RequestBody requestBody, ProgressListener progressListener) {
        this.requestBody = requestBody;
        this.progressListener = progressListener;
    }
    @Override
    public boolean isDuplex() {
        return requestBody.isDuplex();
    }
    @Override
    public boolean isOneShot() {
        return requestBody.isOneShot();
    }
    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }
    @Override
    public long contentLength() throws IOException {
        return requestBody.contentLength();
    }
    @Getter
    class ProgressBufferSink extends ForwardingSink {
        private long bytesWritten = 0;
        private final long contentLength;
        public ProgressBufferSink(Sink delegate, long contentLength) {
            super(delegate);
            this.contentLength = contentLength;
        }
        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            var everyPart = 1024 * 1024;
            var remaining = byteCount;
            notifyProgress();
            while (remaining > 0) {
                var write = Math.min(remaining, everyPart);
                super.write(source, write);
                super.flush();
                remaining -= write;
                bytesWritten += write;
                notifyProgress();
            }
        }
        private void notifyProgress() {
            progressListener.onProgress(bytesWritten, contentLength);
        }
    }
    @Override
    public void writeTo(@NotNull BufferedSink sink) throws IOException {
        BufferedSink progressSink = Okio.buffer(new ProgressBufferSink(sink, contentLength()));
        requestBody.writeTo(progressSink);
        progressSink.flush();
    }
}
